<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-17
 * Time: 16:23
 * 创建项目孵化查看
 */

namespace app\api\service\project;


use app\api\model\ProjectHatch;
use app\api\model\ProjectHatchLook;
use app\api\model\ProjectHatchLookOrder;
use app\api\model\System;
use app\api\service\Token;
use app\lib\exception\ParameterException;

class LookSer extends Token
{
    /**
     * 1.判断用户信息
     * 2.判断时间是否有
     * 3.没有-判断订单是否有
     * 4.没有-提示权限不足
     * 5.有-返回信息
     */

    // 用户ID
    private $uid;

    // 项目孵化ID
    private $projectHatchId;

    function __construct($projectHatchId)
    {
        $this->projectHatchId = $projectHatchId;
        $this->uid = Token::getCurrentUid();
        self::judgeMember();
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeProjectLook();
    }

    // 判断评论权限
    private function judgeProjectLook()
    {
        $time = time();
        $where[] = ['user_id','eq',$this->uid];
        $where[] = ['start_time','elt',$time];
        $where[] = ['end_time','egt',$time];
        $where[] = ['project_hatch_id','egt',$this->projectHatchId];
        $info = ProjectHatchLook::where($where)->find();
        if(!$info) {
            $order = ProjectHatchLookOrder::where('status',2)
                ->where('type',1)
                ->where('user_id',$this->uid)
                ->find();
            if($order) {
                $system = System::get(1);
                $end_time = $time + ($system['project_hatch_look_day']*24*3600);
                $mode = ProjectHatchLook::create([
                    'user_id' => $this->uid,
                    'start_time' => $time,
                    'end_time' => $end_time,
                    'project_hatch_id' => $this->projectHatchId,
                ]);
                $ProjectHatchLookOrder = new ProjectHatchLookOrder();
                $ProjectHatchLookOrder->save([ 'project_hatch_look_id' => $mode->id, 'type'=> 2],[ 'id' => $order['id'] ]);
            } else {
                $projectHatch = ProjectHatch::get($this->projectHatchId);
                if($projectHatch['user_id'] != $this->uid) {
                    throw new ParameterException([
                        'errorCode' => 20007,
                        'msg' => [
                            'hatch' => '您没有项目查看的权限'
                        ]
                    ]);
                }
            }
        }
        return $this->getProjectInfo();
    }

    // 返回项目信息
    private function getProjectInfo()
    {
        return ProjectHatch::with('comments')->where('id',$this->projectHatchId)->find();
    }
}